<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="200px">
      <el-form-item label="校区" prop="shopid" >
        <el-select v-model="dataForm.shopid" placeholder= "校区" @change="getTeachers">
          <el-option v-for="(item, index) in shopids"
                     :label="item.shopName"
                     :key="item.shopName"
                     :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    <el-form-item label="课程名字" prop="name">
      <el-input v-model="dataForm.name" placeholder="课程名字"></el-input>
    </el-form-item>
      <el-form-item label="单节课时" prop="classperiod">
        <el-input v-model="dataForm.classperiod" placeholder="单节课时" type="number"></el-input>
      </el-form-item>
      <el-form-item label="课程时长(分钟)" prop="minutes">
        <el-input v-model="dataForm.minutes" placeholder="课程时长(分钟)" type="number"></el-input>
      </el-form-item>
      <el-form-item label="最大预约人数" prop="limitsnum">
        <el-input v-model="dataForm.limitsnum" placeholder="最大预约人数" type="number"></el-input>
      </el-form-item>
      <el-form-item label="教练姓名" prop="teacherid" >
        <el-select v-model="dataForm.teacherid" placeholder= "选择教练" @change="getTeacherName">
          <el-option v-for="(item, index) in teachers"
                     :label="item.teacherName"
                     :key="item.teacherName"
                     :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上课时间" prop="courseweek">
        <div v-for="(list,index) in dataForm.coursetime"  style="float: left">
          <el-input v-model="list.ids" type="hidden" style="float: left"></el-input>
        <el-time-picker style="width: 150px;" v-model="list.courseweektime" type="datetime" @change="dateChanget" format="HH:mm" value-format="HH:mm" placeholder="选择时间">
        </el-time-picker>
        <el-select class="select-time" v-model="list.courseweek" value-key="id" placeholder="选择周几" @change="dateChanget">
          <el-option v-for="item in payeeoption"
                     :label="item.courseweekname"
                     :key="item.id"
                     :value="item"
          ></el-option>
        </el-select>
        <el-button @click="del(index)" >删除此行</el-button>
        </div>
          </br>
        <div style="float: left"><el-button @click="addDomain" class="btn btn-info">添加</el-button></div>
      </el-form-item>
      <!--
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item label="金额" prop="money">
        <el-input v-model="dataForm.money" placeholder="金额" type="number"></el-input>
      </el-form-item>
      <el-form-item label="支付码" prop="image">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :action="url2"
          :before-upload="beforeUploadHandle"
          :on-success="successHandle">
          <img v-if="imageUrl2" :src="imageUrl2" class="avatar" style="width:200px;height:auto;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<style>
  .select-time{
    width: 150px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          shopid: '',
          name: '',
          total: '',
          pic: '',
          pic2: '',
          teacherid: '',
          teachername: '',
          limitsnum: '',
          content: '',
          begindate: '',
          enddate: '',
          remark: '',
          money: '',
          createtime: '',
          updatetime: '',
          coursetime: [{'courseweek': '', 'courseweektime': ''}],
          classperiod: '',
          minutes: ''
        },
        url: this.$http.adornUrl(`/business/student/uploadPicture?token=${this.$cookie.get('token')}`),
        url2: this.$http.adornUrl(`/business/student/uploadPicture?type=payment&token=${this.$cookie.get('token')}`),
        imageUrl: '',
        imageUrl2: '',
        shopids: '',
        teachers: [],
        changeDate: '',
        oldcoursetime: '',
        stuct: false,
        teacherShopId: '',
        payeeoption: [{'courseweekname': '星期一', 'id': 'Mon'}, {'courseweekname': '星期二', 'id': 'Tue'}, {'courseweekname': '星期三', 'id': 'Wed'}, {'courseweekname': '星期四', 'id': 'Thu'}, {'courseweekname': '星期五', 'id': 'Fri'}, {'courseweekname': '星期六', 'id': 'Sat'}, {'courseweekname': '星期日', 'id': 'Sun'}],
        dataRule: {
          shopid: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '课程名字不能为空', trigger: 'blur' }
          ],
          classperiod: [
            { required: true, message: '单节课时不能为空', trigger: 'blur' }
          ],
          // total: [
          //   { required: true, message: '课程总节数不能为空', trigger: 'blur' }
          // ],
          // pic: [
          //   { required: true, message: '课程配图不能为空', trigger: 'blur' }
          // ],
          // courseweek: [
          //   { required: true, message: '课程时间不能为空', trigger: 'blur' }
          // ],
          teachername: [
            { required: true, message: '老师姓名不能为空', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '课程内容不能为空', trigger: 'blur' }
          ]
          // begindate: [
          //   { required: true, message: '课程开始日期不能为空', trigger: 'blur' }
          // ],
          // enddate: [
          //   { required: true, message: '课程结束日期不能为空', trigger: 'blur' }
          // ],
          // remark: [
          //   { required: true, message: '备注不能为空', trigger: 'blur' }
          // ],
          // createtime: [
          //   { required: true, message: '新增时间不能为空', trigger: 'blur' }
          // ],
          // updatetime: [
          //   { required: true, message: '修改时间不能为空', trigger: 'blur' }
          // ]
        }
      }
    },
    mounted () {
      this.getTeacherInfo()
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/business/course/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.shopid = data.course.shopId
                this.dataForm.name = data.course.name
                this.dataForm.total = data.course.total
                this.dataForm.pic = data.course.pic
                this.dataForm.pic2 = data.course.pic2
                this.dataForm.teacherid = data.course.teacherId
                this.dataForm.teachername = data.course.teacherName
                this.dataForm.limitsnum = data.course.limitsNum
                this.dataForm.content = data.course.content
                this.dataForm.begindate = data.course.beginDate
                this.dataForm.enddate = data.course.endDate
                this.dataForm.remark = data.course.remark
                this.dataForm.money = data.course.money
                this.dataForm.minutes = data.course.minutes
                this.imageUrl = data.course.pic
                this.imageUrl2 = data.course.pic2
                this.dataForm.classperiod = data.course.classPeriod
                this.getOneCourseTime()
                this.qureyCourseInfo()
                // 获取教练
                this.getTeachers(data.course.shopid)
                // this.getOneOldCourseTime()
                this.changeDate = 0
              }
            })
          } else {
            this.stuct = false
            this.dataForm.coursetime = [{'courseweek': '', 'courseweektime': ''}]
            this.imageUrl = ''
            this.imageUrl2 = ''
          }
        })
      },
      // 获取老师的权限
      getTeacherInfo () {
        var userId = this.$store.state.user.id
        this.$http({
          url: this.$http.adornUrl('/business/student/queryTeacherLogin'),
          method: 'get',
          params: {'userId': userId}
        }).then(({data}) => {
          if (data.teacherInfo != null) {
            this.teacherShopId = data.teacherInfo.shopId
          }
          this.getShopInfo()
        })
      },
      addDomain () {
        this.dataForm.coursetime.push({'courseweek': '', 'courseweektime': ''})
      },
      del: function (index) {
        this.dataForm.coursetime.splice(index, 1)
      },
      dateChanget (val) {
        this.changeDate = 1
      },
      // 查询课程的所有课程时间
      getOneCourseTime () {
        let courseid = this.dataForm.id
        this.$http({
          url: this.$http.adornUrl(`/business/course/getCourseTime`),
          method: 'get',
          params: {'id': courseid}
        }).then(({data}) => {
          this.dataForm.coursetime = data.courseTime
          this.changeDate = 0
        })
      },
      // 获取机构下所有店铺信息
      getShopInfo () {
        this.$http({
          url: this.$http.adornUrl('/business/student/getShopInfo'),
          mothod: 'get',
          params: {'shopId': this.teacherShopId}
        }).then(({data}) => {
          this.shopids = data.list
        })
      },
      // 获取店铺下的老师信息
      getTeachers (val) {
        this.$http({
          url: this.$http.adornUrl('/business/teacher/list'),
          mothod: 'get',
          params: {'shopId': val, 'page': '1', 'limit': '100'}
        }).then(({data}) => {
          this.teachers = data.page.list
        })
      },
      // 获取教练名字
      getTeacherName (value) {
        let teacherName = this.teachers.find((item) => {
          return item.teachername === value
        })
        this.dataForm.teachername = teacherName
      },
      qureyCourseInfo () {
        this.$http({
          url: this.$http.adornUrl('/business/course/qureyCourseInfo'),
          method: 'get',
          params: {'courseId': this.dataForm.id}
        }).then(({data}) => {
          if (data.count > 0) {
            this.stuct = true
          } else {
            this.stuct = false
          }
        })
      },
      beforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        if (file.size / 1024 / 1024 > 2) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
          return false
        }
        this.num++
      },
      // 上传成功
      successHandle (response) {
        this.successNum++
        if (response && response.code === 0) {
          alert('操作成功, 请继续填写其他信息!')
          // this.imageUrl = response.url
          // this.dataForm.pic = response.url

            // this.imageUrl2 = response.url
            // this.dataForm.pic2 = response.url
          if (response.type === 'payment') {
            this.imageUrl2 = response.url
            this.dataForm.pic2 = response.url
          } else {
            this.imageUrl = response.url
            this.dataForm.pic = response.url
          }
        }
      },
      // 表单提交
      dataFormSubmit () {
        if (this.state && this.changeDate === 1) {
          this.$confirm(`此课程已有学生预约，确定更改上课时间?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                this.$http({
                  url: this.$http.adornUrl(`/business/course/${!this.dataForm.id ? 'save' : 'update'}`),
                  method: 'post',
                  data: this.$http.adornData({
                    'id': this.dataForm.id || undefined,
                    'shopId': this.dataForm.shopid,
                    'name': this.dataForm.name,
                    'total': this.dataForm.total,
                    'pic': this.dataForm.pic,
                    'pic2': this.dataForm.pic2,
                    'teacherId': this.dataForm.teacherid,
                    'teacherName': this.dataForm.teachername,
                    'limitsNum': this.dataForm.limitsnum,
                    'content': this.dataForm.content,
                    'beginDate': this.dataForm.begindate,
                    'endDate': this.dataForm.enddate,
                    'remark': this.dataForm.remark,
                    'money': this.dataForm.money,
                    'createTime': this.dataForm.createtime,
                    'updateTime': this.dataForm.updatetime,
                    'stuct': this.stuct,
                    'classPeriod': this.dataForm.classperiod,
                    'minutes': this.dataForm.minutes
                  })
                }).then(({data}) => {
                  if (data && data.code === 0) {
                    this.$message({
                      message: '操作成功',
                      type: 'success',
                      duration: 1500,
                      onClose: () => {
                        this.visible = false
                        this.$emit('refreshDataList')
                      }
                    })
                  } else {
                    this.$message.error(data.msg)
                  }
                })
              }
            })
          })
        } else {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.$http({
                url: this.$http.adornUrl(`/business/course/${!this.dataForm.id ? 'save' : 'update'}`),
                method: 'post',
                data: this.$http.adornData({
                  'id': this.dataForm.id || undefined,
                  'shopId': this.dataForm.shopid,
                  'name': this.dataForm.name,
                  'total': this.dataForm.total,
                  'pic': this.dataForm.pic,
                  'pic2': this.dataForm.pic2,
                  'teacherId': this.dataForm.teacherid,
                  'teacherName': this.dataForm.teachername,
                  'limitsNum': this.dataForm.limitsnum,
                  'content': this.dataForm.content,
                  'beginDate': this.dataForm.begindate,
                  'endDate': this.dataForm.enddate,
                  'remark': this.dataForm.remark,
                  'money': this.dataForm.money,
                  'coursetime': this.dataForm.coursetime,
                  'stuct': this.stuct,
                  'classPeriod': this.dataForm.classperiod,
                  'minutes': this.dataForm.minutes
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.$emit('refreshDataList')
                    }
                  })
                } else {
                  this.$message.error(data.msg)
                }
              })
            }
          })
        }
      }
    }
  }
</script>
